<?php

namespace app\admin\model;

use app\admin\model\activity\Tuangou;
use app\admin\model\order\Order;
use app\common\model\Sms;
use think\Db;
use think\Exception;
use think\Model;


class SpellOrder extends Model
{





    // 表名
    protected $name = 'spell_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'finishTime_text',
        'payTime_text',
        'ctime_text'
    ];






    public function getFinishtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['finishTime']) ? $data['finishTime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['payTime']) ? $data['payTime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['ctime']) ? $data['ctime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setFinishtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    /**
     * 订单退款状态
     */
    public static function returnStatusInfo()
    {
        return [
            0=>'申请退换货',
            1=>'退换货中',
            2=>'已退换货',
        ];
    }
    /**
     * 订单状态
     */
    public function orderStatusInfo($model = 1)
    {
        $statusInfo = array(
            0=>'失效订单',
            9=>'已评论',
            10=>"已取消",
        );
        if($model == 1){
            return $statusInfo+[
                1=>'待支付',
                2=>'已支付',
                5=>'已发货',
                6=>'已完成'
            ];
        }elseif($model == 2){
            return $statusInfo+[
                1=>'待支付',
                2=>'拼团中',
                3=>'已成团',
                4=>'确认发货',
                5=>'已发货',
                6=>'已完成',
                7=>'已回购',
            ];
        }elseif($model == 3){
            return $statusInfo+[
                1=>'待支付',
                2=>'拼团中',
                3=>'拼购成功',
                4=>'确认发货',
                5=>'已发货',
                6=>'已完成',
//                7=>'已回购',
                11=>'寄售中',
                12=>'寄售完成'
            ];
        }
    }
    /**
     * 订单支付成功
     */
    public static function startPay($orderId, $transaction_id, $payType)
    {
        $re = self::where('orderId',$orderId)->where('payStatus',0)->update([
            "payType"=>$payType,
            "payTime"=>time(),
            "payStatus"=>1,
            "transaction_id"=>$transaction_id,
            "orderStatus"=>2,
            "updatetime"=>time(),
        ]);
        if($re == false){
            throw new \think\Exception("订单更新失败");
        }
        $orderInfo = self::where('orderId',$orderId)->where('payStatus',1)->where('orderStatus',2)->find();

        if(empty($orderInfo)){
            throw new \think\Exception("订单获取失败");
        }
        if ($orderInfo['model'] == 1) {
            self::where(['orderId'=>$orderId])->update(['orderStatus'=>4]);
        }
        if ($orderInfo['model'] == 2) {
            \app\admin\model\spell\Spell::startSpell($orderInfo);
            Db::table('pt_rebate_queue')->insert(['orderId'=>$orderId,'ctime'=>time()]);
        }
        if ($orderInfo['model'] == 3) {
            $promInfo=Tuangou::get(['id'=>$orderInfo['actid']]);
            $pnum=$promInfo['pnum']+$orderInfo['goodsNum'];
            $status=$pnum>=$promInfo['zcount']?2:1;
            if($status==2){ //拼团完成更新所有订单状态
                $days = \think\config::get("site.saleDays");
                $finishtime=time()+$days*86400;
                $res=self::update(['orderStatus'=>11,'finishtime'=>$finishtime],['actid'=>$orderInfo['actid']]);
                Tuangou::update(['pnum'=>$pnum,'status'=>$status,'finish_time'=>time()],['id'=>$orderInfo['actid'],'status'=>1]);
                $list=Order::all(['actid'=>$orderInfo['actid']]);
                foreach ($list as $row){
                    \app\common\library\Sms::otherSend([
                        "uid"=>$row['uid'],
                        "type"=>10,
                        "days"=>$days,
                        "income"=>bcmul($row['payPrice'],$promInfo['rate']*0.01,2),
                    ]);
                }
            }else{
                Tuangou::update(['pnum'=>$pnum],['id'=>$orderInfo['actid'],'status'=>1]);
                //成团发送拼团短信
                \app\common\library\Sms::otherSend([
                    "uid"=>$orderInfo['uid'],
                    "type"=>9,
                    "price"=>$orderInfo['payPrice'],
                    "income"=>bcmul($orderInfo['payPrice'],$promInfo['rate']*0.01,2),
                ]);

            }

            Db::table('pt_rebate_queue')->insert(['orderId'=>$orderId,'ctime'=>time()]);
        }
        //多商品购买，清除购物车数据
       // self::deleteCart($orderId);
        //有效用户统计
        \app\admin\model\agent\Valid::userUpdate($orderInfo);
    }
    /**
     * 快递信息获取
     */
    public function getExpressList($orderInfo)
    {
        $data = [];
        $status = \think\config::get("site.expressstatus");
        $expresskey = \think\config::get("site.expresskey");
        $expresscustomer = \think\config::get("site.expresscustomer");
        if(empty($status) || empty($expresskey) || empty($expresscustomer)){
            return $data;
        }
        $result = \fast\Http::get("https://m.kuaidi100.com/apicenter/kdquerytools.do?method=autoComNum&text=".$orderInfo['expressNo']);
        $dataInfo = json_decode($result,true);
        if(empty($dataInfo['auto'][0]['comCode'])){
            return $data;
        }
        $json=json_encode(['com'=>$dataInfo['auto'][0]['comCode'],'num'=>$orderInfo['expressNo'],'phone' => '', 'from' => '','to' => '','resultv2' => '1'],true);
        $sign=strtoupper(md5($json.$expresskey.$expresscustomer));
        $url = "http://poll.kuaidi100.com/poll/query.do?customer=".$expresscustomer."&sign=".$sign."&param=".$json;
        $result = \fast\Http::get($url);
        $dataInfo = json_decode($result,true);
        if($dataInfo['message'] == 'ok' && $dataInfo['status'] == '200'){
            return $dataInfo['data'];
        }
        return $data;
    }
    /**
     * 自动确认收货
     */
    public static function crontab($uid = 0)
    {
        $day = \think\config::get("site.pingorderautoorder");
        if($day<=0){
            return true;
        }
        $time = time() - $day*24*3600;
        $model = new self();
        $query = $model->where('orderStatus',5);
        if(!empty($uid)){
            $query->where('uid',$uid);
        }
        $list = $query->where('delivertime','>',0)->where('delivertime','<',$time)->select();
        if(empty($list)){
            return true;
        }
        foreach ($list as $ks=>$vs){
            $vs->save(['orderStatus'=>6,'finishtime'=>time()]);
        }
        return true;
    }

    /**
     * 寄售返佣
     */
    public static function setRebate($uid)
    {
        $days = \think\config::get("site.saleDays");
        $list=SpellOrder::where(['uid'=>$uid,'orderStatus'=>11])->where('finishtime','<=',strtotime(date('Ymd')))->select();
        if(empty($list)) return false;
        foreach ($list as $row){
            SpellOrder::update(['orderStatus'=>12],['orderId'=>$row['orderId']]);
            $rate=Tuangou::where(['id'=>$row['actid']])->value('rate');
            \app\admin\model\rebate\Rebate::saveRebateInfo([
                "uid" => $row['uid'],
                "disUid" => $row['uid'],
                "orderId" => $row['orderId'],
                "oid" => $row['orderId'],
                "type" => 20,
                "percent" => 10,
                "price" => bcmul($row['payPrice'],$rate*0.01,2),
                "info" => '寄售收入',
            ]);

            \app\common\library\Sms::otherSend([
                "uid"=>$row['uid'],
                "type"=>12,
                "income"=>bcmul($row['payPrice'],$rate*0.01,2),
            ]);
        }
    }
    /**
     * 清除购物车数据
     */
    public static function deleteCart($orderId)
    {
        $list = Db::query("SELECT * FROM `pt_spell_detail` WHERE orderId='{$orderId}'" );
        if(!empty($list) && count($list)>1){
            foreach ($list as $ks=>$vs){
                Db::query("UPDATE `pt_cart` SET status=9 WHERE uid='{$vs['uid']}' AND goodsId='{$vs['goodsId']}' AND skuId='{$vs['skuId']}'");
            }
        }
        return true;
    }
}
